package com.fdb.efp.console.api.rest;

import com.fdb.basic.framework.core.constant.ApplicationConstance;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.basic.framework.core.vo.EngineHttpRequestVO;
import com.fdb.basic.framework.web.util.HttpClientUtil;
import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.service.facade.PubSysInfoService;
import com.fdb.efp.console.executor.util.AbstractController;
import com.fdb.efp.console.service.FlowCommonService;
import com.fdb.efp.console.service.FlowRepulseUtil;
import com.fdb.efp.console.service.facade.BizFlowInfoService;
import com.fdb.efp.console.service.facade.FlowUrlConfigService;
import com.fdb.efp.console.common.RiskColltConstant;
import com.fdb.efp.console.service.facade.ColltTaskFlowAppService;
import com.fdb.efp.console.service.facade.ColltTaskInfoService;
import com.fdb.efp.console.service.vo.ColltTaskFlowAppVO;
import com.fdb.efp.console.service.vo.ColltTaskInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * 需求编号：【】（业务提的需求编号）
 * 问题编号：【】（若不是因为修复问题而新增该类，则留空）
 * 开发人员：【wanglihua】
 * 创建日期：【2019/9/18 19:31】
 * 功能描述：
 */
@RestController
@RequestMapping("/api")
public class LitigationFlowController extends AbstractController {

    @Autowired
    @Qualifier("colltTaskFlowAppService")
    private ColltTaskFlowAppService colltTaskFlowAppService;

    @Autowired
    @Qualifier("bizFlowInfoService")
    private BizFlowInfoService bizFlowInfoService;

    @Autowired
    @Qualifier("pubSysInfoService")
    private PubSysInfoService pubSysInfoService;

    @Autowired
    @Qualifier("flowUrlConfigService")
    private FlowUrlConfigService flowUrlConfigService;

    @Autowired
    @Qualifier("colltTaskInfoService")
    private ColltTaskInfoService colltTaskInfoService;

    @Autowired
    private FlowCommonService flowCommonService;

    @Autowired
    @Qualifier("flowRepulseUtil")
    private FlowRepulseUtil flowRepulseUtil;

    @RequestMapping(value = "/collt/litiTask/flow/commit", method = RequestMethod.GET)
    public @ResponseBody
    ResponseData<Integer> submitLitigInfos(@RequestParam(value = "flowApplyNo", required = true) String flowApplyNo) {

        logger.info("即将发起诉讼催收审批流程，流转申请编号为:" + flowApplyNo);
        int outputVo = 0;
        try {
            String eventId = "litigationFlowEnter";

            //根据流转申请编号获取催收任务流转信息
            ColltTaskFlowAppVO colltTaskFlowAppVo = Optional.ofNullable(colltTaskFlowAppService.queryByFlowApplyNo(flowApplyNo)).orElseGet(ColltTaskFlowAppVO::new);

            if(colltTaskFlowAppVo.getApproveStatus().equals(ConsoleConstant.APRV_STATUS_05)){
                flowRepulseUtil.cleanRepulseAllInfo(flowApplyNo);
            }
            //审批状态置为“审批中”
            colltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_02);

            //获取流程信息
//        BizFlowInfoVO bizFlowInfoVO = new BizFlowInfoVO();
//        bizFlowInfoVO.setBizFlowType(FlowConstance.BIZ_FLOW_TYPE_10);
//        List<BizFlowInfoVO> listFlow = bizFlowInfoService.queryBizFlowInfoByFlowType(bizFlowInfoVO);

            //获取流程ID,若获取到的流程信息为空，则置审批状态为“待发起”
            String flowId = "FW20190918000000013";
            if (!flowCommonService.dutyFlowCheck(eventId,flowId)){
                outputVo = -1;
                String message = "发起风险分类调整申请审批流程失败!原因: 流程岗位已失效!";
                return setResponseMessage(outputVo,message, ApplicationConstance.FAILURE, false);
            }
            if (StringUtil.isNullorBank(flowId)) {
                //更新审核状态为待发起
                colltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
                int num = colltTaskFlowAppService.updateByPk(colltTaskFlowAppVo);
                if (num < 0) {
                    logger.error("更新审核状态失败！");
                }
                //设置返回信息
                outputVo = -1;
                String message = "未配置相关信息,提交失败!";
                return setResponseMessage(outputVo, message, ApplicationConstance.FAILURE, false);
            }
//        if (Objects.nonNull(listFlow) && listFlow.size() > 0) {
//            bizFlowInfoVO = listFlow.get(0);
//            flowId = bizFlowInfoVO.getBizFlowId();  // 得到业务流转ID
//        } else {
//            //更新审核状态为待发起
//            colltTaskFlowAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
//            int num = colltTaskFlowAppService.updateByPk(colltTaskFlowAppVo);
//            if (num < 0) {
//                logger.error("更新审核状态失败！");
//            }
//            //设置返回信息
//            outputVo = -1;
//            String message = "未配置相关信息,提交失败!";
//            return setResponseMessage(message, ApplicationConstance.FAILURE,false);
//        }

            EngineHttpRequestVO eVo = new EngineHttpRequestVO();
            // 业务法人机构
            eVo.setBizLagelOrgCode(this.getUserInfo().getOrgInfo().getOrgCode());
            // 业务流水号
            eVo.setE_bizSerno(colltTaskFlowAppVo.getFlowApplyNo());
            eVo.setFlowId(flowId);
            //事件ID
            eVo.setData(colltTaskFlowAppVo);
            eVo.setEventId(eventId);
            eVo.setG_bizSerno(colltTaskFlowAppVo.getFlowApplyNo());


            HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
            //设置审批时间
            colltTaskFlowAppVo.setAprvTime(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
            outputVo = colltTaskFlowAppService.updateByPk(colltTaskFlowAppVo);

            if (outputVo > 0) {
                int flagNum = 0;
                //更新任务状态为“流转中”
                ColltTaskInfoVO colltTaskInfoVo = new ColltTaskInfoVO();
                colltTaskInfoVo.setTaskSts(RiskColltConstant.COLLT_OUTS_TASK_STS_05);
                colltTaskInfoVo.setColltTaskNo(colltTaskFlowAppVo.getColltTaskNo());
                flagNum = colltTaskInfoService.updateByPk(colltTaskInfoVo);
                if (flagNum < 0) {
                    logger.error("更新任务状态为“流转中”失败！");
                }
            }
        } catch (Exception e) {
            // 发起失败
            e.printStackTrace();
            outputVo = -1;
            logger.error("ColltTaskFlowAppVO", e.getMessage());
            String message = "发起诉讼催收审批流程失败!原因:" + e.getMessage();
            return setResponseMessage(outputVo, message, ApplicationConstance.FAILURE, false);
        }
        return getResponseData(outputVo);
    }

    private ResponseData<Integer> setResponseMessage(int outputVo ,String message, String code, boolean isSuccess) {
        ResponseData<Integer> responseData = new ResponseData<Integer>();
        responseData.setRows(outputVo);
        responseData.setMessage(message);
        responseData.setCode(code);
        responseData.setSuccess(isSuccess);
        return responseData;
    }
}
